package top.kaoshanji.p1ch03a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 代码清单 p1ch03a-07：打开文件通道并写入数据的示例
 * author kaoshanji
 * ^_^
 * create time 2025/1/6 18:47
 */
public class FileChannelExample01 {

    private static final Logger logger = LogManager.getLogger(FileChannelExample01.class);

    public static void main(String[] args) throws IOException {
        logger.info("...代码清单 p1ch03a-07：打开文件通道并写入数据的示例...");

        // StandardOpenOption.CREATE 如果文件不存在，就创建一个新文件
        // StandardOpenOption.WRITE 允许写入

        // 通过直接打开文件来创建文件通道
        FileChannel channel = FileChannel.open(Paths.get(FileConstant.LOCAL_ROOT_PATH.concat("p1ch03a07.txt")),
                StandardOpenOption.CREATE, StandardOpenOption.WRITE);

        ByteBuffer buffer = ByteBuffer.allocate(64);
        buffer.putChar('A').flip();

        channel.write(buffer); // 需要刷新一下？
        // channel.force(true); // 强制写入磁盘（包含文件元数据）

        channel.close();
    }

}
